#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A股智能预测分析系统 - 实时验证脚本
目标：验证系统能否帮助您增加股票投资获利概率

测试重点：
1. 数据获取 - 确保能获取实时股票数据
2. 技术分析 - 验证买卖信号准确性
3. 预测模型 - 测试多模型预测功能
4. 选股系统 - 找到优质投资标的
5. 风险评估 - 控制投资风险
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from data_fetcher import StockDataFetcher
from technical_analysis import TechnicalAnalysis
from prediction_model import PredictionModel
from stock_screener import StockScreener

class LiveSystemValidator:
    def __init__(self):
        self.data_fetcher = StockDataFetcher()
        self.technical_analysis = TechnicalAnalysis()
        self.prediction_model = PredictionModel()
        self.stock_screener = StockScreener()
        
        # 测试股票列表 - 选择不同类型的股票进行测试
        self.test_stocks = {
            '000001': '平安银行 (大盘银行股)',
            '600519': '贵州茅台 (白酒龙头)',
            '000002': '万科A (地产龙头)', 
            '600036': '招商银行 (银行龙头)',
            '002475': '立讯精密 (科技股)'
        }
        
        self.results = {}
        
    def print_header(self, title):
        print(f"\n{'='*60}")
        print(f"🎯 {title}")
        print(f"{'='*60}")
        
    def print_success(self, message):
        print(f"✅ {message}")
        
    def print_error(self, message):
        print(f"❌ {message}")
        
    def print_info(self, message):
        print(f"📊 {message}")
        
    def test_data_fetching(self):
        """测试数据获取功能"""
        self.print_header("数据获取功能测试")
        
        try:
            # 获取股票列表
            stock_list = self.data_fetcher.get_stock_list()
            if len(stock_list) > 0:
                self.print_success(f"股票列表获取成功: {len(stock_list)} 只股票")
            else:
                self.print_error("股票列表获取失败")
                return False
                
            # 测试单个股票数据获取
            test_code = '000001'
            stock_data = self.data_fetcher.get_stock_data(test_code, days=30)
            
            if not stock_data.empty:
                latest_price = stock_data['close'].iloc[-1]
                self.print_success(f"股票数据获取成功: {test_code} 最新价格 ¥{latest_price:.2f}")
                self.print_info(f"数据条数: {len(stock_data)} 条")
                return True
            else:
                self.print_error(f"股票 {test_code} 数据获取失败")
                return False
                
        except Exception as e:
            self.print_error(f"数据获取测试失败: {e}")
            return False
    
    def test_technical_analysis(self):
        """测试技术分析功能"""
        self.print_header("技术分析功能测试")
        
        try:
            test_code = '000001'
            stock_data = self.data_fetcher.get_stock_data(test_code, days=60)
            
            if stock_data.empty:
                self.print_error("无法获取股票数据进行技术分析")
                return False
            
            # 计算技术指标
            indicators = self.technical_analysis.calculate_indicators(stock_data)
            
            if indicators:
                self.print_success("技术指标计算成功")
                
                # 检查关键指标
                if 'buy_line' in indicators and not indicators['buy_line'].empty:
                    self.print_info(f"买线数据: {len(indicators['buy_line'])} 个数据点")
                    
                if 'sell_line' in indicators and not indicators['sell_line'].empty:
                    self.print_info(f"卖线数据: {len(indicators['sell_line'])} 个数据点")
                
                # 获取交易信号
                signal = self.technical_analysis.get_trading_signal(stock_data)
                self.print_success(f"交易信号: {signal}")
                
                return True
            else:
                self.print_error("技术指标计算失败")
                return False
                
        except Exception as e:
            self.print_error(f"技术分析测试失败: {e}")
            return False
    
    def test_prediction_model(self):
        """测试预测模型功能"""
        self.print_header("预测模型功能测试")
        
        try:
            test_code = '000001'
            stock_data = self.data_fetcher.get_stock_data(test_code, days=120)
            
            if stock_data.empty:
                self.print_error("无法获取足够的历史数据进行预测")
                return False
            
            # 进行价格预测
            prediction = self.prediction_model.predict_price(stock_data, test_code)
            
            if prediction and 'trend' in prediction:
                self.print_success("价格预测成功")
                self.print_info(f"预测趋势: {prediction['trend']}")
                self.print_info(f"置信度: {prediction.get('confidence', 0):.1%}")
                
                if 'next_day_price' in prediction:
                    current_price = stock_data['close'].iloc[-1]
                    predicted_price = prediction['next_day_price']
                    change_pct = (predicted_price - current_price) / current_price * 100
                    
                    self.print_info(f"当前价格: ¥{current_price:.2f}")
                    self.print_info(f"预测价格: ¥{predicted_price:.2f}")
                    self.print_info(f"预期涨跌: {change_pct:+.2f}%")
                
                return True
            else:
                self.print_error("预测模型返回结果异常")
                return False
                
        except Exception as e:
            self.print_error(f"预测模型测试失败: {e}")
            return False
    
    def test_stock_screening(self):
        """测试智能选股功能"""
        self.print_header("智能选股功能测试")
        
        try:
            # 设置筛选条件
            criteria = {
                'min_market_cap': 50,  # 50亿市值
                'max_pe_ratio': 30,    # 市盈率小于30
                'min_volume_ratio': 1.0,  # 成交量放大
                'dividend_required': False,  # 不强制要求分红
            }
            
            # 进行选股（测试少量股票以加快速度）
            test_stocks = ['000001', '600519', '000002', '600036', '002475']
            screened_stocks = self.stock_screener.screen_stocks(
                criteria=criteria, 
                stock_codes=test_stocks
            )
            
            if screened_stocks is not None and len(screened_stocks) > 0:
                self.print_success(f"智能选股成功: 筛选出 {len(screened_stocks)} 只股票")
                
                # 显示前3只推荐股票
                top_stocks = screened_stocks.head(3)
                for idx, (_, stock) in enumerate(top_stocks.iterrows(), 1):
                    self.print_info(f"推荐 #{idx}: {stock['code']} - {stock['name']}")
                    self.print_info(f"  综合评分: {stock.get('total_score', 0):.1f}")
                    self.print_info(f"  当前价格: ¥{stock.get('current_price', 0):.2f}")
                
                return True
            else:
                self.print_error("智能选股未找到符合条件的股票")
                return False
                
        except Exception as e:
            self.print_error(f"智能选股测试失败: {e}")
            return False
    
    def test_complete_analysis_workflow(self):
        """测试完整的股票分析工作流程"""
        self.print_header("完整分析工作流程测试")
        
        success_count = 0
        total_stocks = len(self.test_stocks)
        
        for stock_code, stock_name in self.test_stocks.items():
            print(f"\n📈 分析股票: {stock_code} - {stock_name}")
            
            try:
                # 1. 获取数据
                stock_data = self.data_fetcher.get_stock_data(stock_code, days=90)
                if stock_data.empty:
                    print(f"  ❌ 数据获取失败")
                    continue
                
                current_price = stock_data['close'].iloc[-1]
                print(f"  💰 当前价格: ¥{current_price:.2f}")
                
                # 2. 技术分析
                signal = self.technical_analysis.get_trading_signal(stock_data)
                print(f"  📊 技术信号: {signal}")
                
                # 3. 价格预测
                prediction = self.prediction_model.predict_price(stock_data, stock_code)
                if prediction and 'trend' in prediction:
                    trend = prediction['trend']
                    confidence = prediction.get('confidence', 0)
                    print(f"  🔮 预测趋势: {trend} (置信度: {confidence:.1%})")
                    
                    # 计算投资建议
                    if trend == '上涨' and confidence > 0.3:
                        if signal in ['买入', '强烈买入']:
                            advice = "🟢 建议买入"
                        else:
                            advice = "🟡 谨慎观察"
                    elif trend == '下跌':
                        advice = "🔴 建议回避"
                    else:
                        advice = "🟡 持币观望"
                    
                    print(f"  💡 投资建议: {advice}")
                    
                success_count += 1
                
            except Exception as e:
                print(f"  ❌ 分析失败: {e}")
        
        success_rate = success_count / total_stocks * 100
        if success_rate >= 80:
            self.print_success(f"完整工作流程测试通过: {success_count}/{total_stocks} ({success_rate:.1f}%)")
            return True
        else:
            self.print_error(f"完整工作流程测试未达标: {success_count}/{total_stocks} ({success_rate:.1f}%)")
            return False
    
    def run_all_tests(self):
        """运行所有测试"""
        print(f"""
🎯 A股智能预测分析系统 - 实时验证测试
📅 测试时间: {datetime.now().strftime('%Y年%m月%d日 %H:%M')}
🎪 测试目的: 验证系统能否帮助您增加投资获利概率

🚀 开始全面测试...
        """)
        
        tests = [
            ('数据获取', self.test_data_fetching),
            ('技术分析', self.test_technical_analysis), 
            ('预测模型', self.test_prediction_model),
            ('智能选股', self.test_stock_screening),
            ('完整流程', self.test_complete_analysis_workflow)
        ]
        
        passed_tests = 0
        total_tests = len(tests)
        
        for test_name, test_func in tests:
            try:
                if test_func():
                    passed_tests += 1
                    self.results[test_name] = True
                else:
                    self.results[test_name] = False
            except Exception as e:
                self.print_error(f"{test_name}测试异常: {e}")
                self.results[test_name] = False
        
        # 测试结果总结
        self.print_header("测试结果总结")
        
        pass_rate = passed_tests / total_tests * 100
        
        print(f"📊 测试通过率: {passed_tests}/{total_tests} ({pass_rate:.1f}%)")
        
        for test_name, result in self.results.items():
            status = "✅ 通过" if result else "❌ 失败"
            print(f"  {test_name}: {status}")
        
        if pass_rate >= 80:
            print(f"""
🎉 系统验证成功！

🏆 您的A股智能预测分析系统已经ready！
💡 系统功能完整，可以开始辅助您的股票投资决策
📈 Web界面地址: http://localhost:8501

🚀 建议使用流程：
1. 访问 http://localhost:8501
2. 在首页输入股票代码（如：000001）
3. 查看技术分析和预测结果
4. 使用智能选股发现投资机会
5. 结合多个指标做出投资决策

⚠️  投资提醒：
- 系统预测仅供参考，不构成投资建议
- 股市有风险，投资需谨慎
- 建议分散投资，控制仓位
- 设置止损点，保护资金安全
            """)
            return True
        else:
            print(f"""
⚠️  系统验证未完全通过

🔧 当前系统功能可能存在问题，建议检查：
1. 网络连接是否正常
2. 数据源接口是否可用
3. 相关依赖包是否正确安装

📞 如需技术支持，请检查错误日志
            """)
            return False

if __name__ == "__main__":
    validator = LiveSystemValidator()
    validator.run_all_tests()
